<script setup>
import { ref, onMounted, computed} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getFoodDetailService, getFoodByKeywordService } from '@/api/food.js'
import { Loading, ArrowDown, Back, Timer, Star, Plus, Search, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const foodDetail = ref(null)
const loading = ref(true)
const showAllNutrition = ref(false)
const energyUnit = ref('kcal')
const dialogVisible = ref(false)
const searchKeyword = ref('')
const searchResults = ref([])
const selectedFoods = ref([])
const searching = ref(false)

// 计算三大营养素供能比
const nutritionRatio = computed(() => {
  if (!foodDetail.value) return { protein: 0, fat: 0, carbs: 0 }
  
  const protein = parseFloat(foodDetail.value.nutritionComponents.find(n => n.nameEn === 'protein')?.content || '0')
  const fat = parseFloat(foodDetail.value.nutritionComponents.find(n => n.nameEn === 'fat')?.content || '0')
  const carbs = parseFloat(foodDetail.value.nutritionComponents.find(n => n.nameEn === 'CHO')?.content || '0')
  
  const total = protein * 4 + fat * 9 + carbs * 4
  
  return {
    protein: ((protein * 4 / total) * 100).toFixed(1),
    fat: ((fat * 9 / total) * 100).toFixed(1),
    carbs: ((carbs * 4 / total) * 100).toFixed(1)
  }
})

// 计算要显示的营养成分
const displayedNutrition = computed(() => {
  if (!foodDetail.value) return []
  const nutrition = foodDetail.value.nutritionComponents
  return showAllNutrition.value ? nutrition : nutrition.slice(0, 10)
})

// 获取状态标签
const getStatusInfo = (status) => {
  const statusMap = {
    0: { label: '偏低', color: '#409EFF', icon: '↓' },
    1: { label: '正常', color: '#67C23A', icon: '─' },
    2: { label: '偏高', color: '#E6A23C', icon: '↑' }
  }
  return statusMap[status] || statusMap[1]
}

const fetchFoodDetail = async () => {
  try {
    loading.value = true
    const result = await getFoodDetailService(route.params.id)
    foodDetail.value = result.data
    console.log(foodDetail.value)
    document.title = result.data.foodName
  } catch (error) {
    console.error('获取食品详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 计算能量值
const energy = computed(() => {
  if (!foodDetail.value) return { kj: 0, kcal: 0 }
  const energyData = foodDetail.value.nutritionComponents.find(n => n.nameEn === 'energy')
  const kj = parseFloat(energyData?.content || '0')
  return {
    kj: kj.toFixed(1),
    kcal: (kj / 4.184).toFixed(1)
  }
})

// 计算能量进度条的百分比
const energyPercentage = computed(() => {
  const kj = parseFloat(energy.value.kj)
  if (kj < 628) return 0
  if (kj > 1674) return 100
  return ((kj - 628) / (1674 - 628) * 100).toFixed(1)
})

// 计算过滤后的搜索结果（排除已选择的食品）
const filteredSearchResults = computed(() => {
  return searchResults.value.filter(food => 
    !selectedFoods.value.some(selected => selected.id === food.id)
  )
})

// 添加到对比列表
const addToCompare = (food) => {
  if (selectedFoods.value.length >= 4) {
    ElMessage.warning('最多只能对比5个食品')
    return
  }
  selectedFoods.value.push(food)
}

// 从对比列表中移除
const removeFood = (food) => {
  selectedFoods.value = selectedFoods.value.filter(f => f.id !== food.id)
}

// 显示对比对话框
const showCompareDialog = () => {
  dialogVisible.value = true
  searchKeyword.value = ''
  searchResults.value = []
  selectedFoods.value = []
}

// 处理搜索
const handleSearch = async () => {
  if (!searchKeyword.value) {
    searchResults.value = []
    return
  }
  
  try {
    searching.value = true
    const result = await getFoodByKeywordService(searchKeyword.value)
    // 过滤掉当前食品
    searchResults.value = result.data.filter(food => food.id !== foodDetail.value?.id)
  } catch (error) {
    console.error('搜索食品失败:', error)
    ElMessage.error('搜索食品失败')
  } finally {
    searching.value = false
  }
}

// 处理对比
const handleCompare = () => {
  if (selectedFoods.value.length === 0) return
  
  const foodIds = [foodDetail.value.id, ...selectedFoods.value.map(f => f.id)].join(',')
  router.push(`/food-compare?foods=${foodIds}`)
}

onMounted(() => {
  fetchFoodDetail()
})
</script>

<template>
  <div class="food-detail-page">
    <!-- 返回按钮 -->
    <div class="back-button">
      <el-button @click="goBack" icon="Back" size="large">
        返回
      </el-button>
    </div>

    <!-- 使用 v-if/v-else-if/v-else 结构 -->
    <template v-if="loading">
      <el-card class="loading-card">
        <el-icon class="loading-icon"><Loading /></el-icon>
        加载中...
      </el-card>
    </template>

    <template v-else-if="foodDetail">
      <!-- 顶部信息区域 -->
      <div class="top-section">
        <div class="food-basic-info">
          <img :src="foodDetail.picture" :alt="foodDetail.foodName" class="food-image">
          <div class="info-content">
            <div class="title-row">
              <h1>{{ foodDetail.foodName }}</h1>
              <el-button 
                type="primary" 
                class="compare-button"
                @click="showCompareDialog"
              >
                <el-icon><Plus /></el-icon>
                添加食品对比
              </el-button>
            </div>
            <el-tag size="large">{{ foodDetail.foodType.type }}</el-tag>
            <p class="description">{{ foodDetail.description || '暂无描述' }}</p>
          </div>
        </div>
      </div>

      <!-- 能量信息卡片 -->
      <div class="energy-section">
        <h2>能量（每100克可食部）</h2>
        <div class="energy-display">
          <div class="energy-buttons">
            <el-radio-group v-model="energyUnit" size="large">
              <el-radio-button label="kcal">千卡</el-radio-button>
              <el-radio-button label="kj">千焦</el-radio-button>
            </el-radio-group>
          </div>
          <div class="energy-value-display">
            <div class="energy-number">{{ energyUnit === 'kcal' ? energy.kcal : energy.kj }}</div>
            <div class="energy-unit">{{ energyUnit === 'kcal' ? '千卡(kcal)' : '千焦(kJ)' }}</div>
          </div>
          <el-progress
            :percentage="energyPercentage"
            :color="[
              { percentage: 50, color: '#67C23A' }, // 青色
              { percentage: 100, color: '#E6A23C' } // 橙色
            ]"
            :stroke-width="20"
            show-text
          />
        </div>
      </div>

      <!-- 营养素比例区域 -->
      <div class="nutrition-ratio-section">
        <h2>三大营养素供能比</h2>
        <div class="ratio-circles">
          <div class="circle-item">
            <el-progress
              type="circle"
              :percentage="parseFloat(nutritionRatio.protein)"
              :color="'#FF9F7F'"
              :stroke-width="10"
            >
              <template #default="{ percentage }">
                <h4>蛋白质</h4>
                <div class="circle-value">{{ percentage }}%</div>
              </template>
            </el-progress>
          </div>
          <div class="circle-item">
            <el-progress
              type="circle"
              :percentage="parseFloat(nutritionRatio.fat)"
              :color="'#FFE434'"
              :stroke-width="10"
            >
              <template #default="{ percentage }">
                <h4>脂肪</h4>
                <div class="circle-value">{{ percentage }}%</div>
              </template>
            </el-progress>
          </div>
          <div class="circle-item">
            <el-progress
              type="circle"
              :percentage="parseFloat(nutritionRatio.carbs)"
              :color="'#37A2DA'"
              :stroke-width="10"
            >
              <template #default="{ percentage }">
                <h4>碳水化合物</h4>
                <div class="circle-value">{{ percentage }}%</div>
              </template>
            </el-progress>
          </div>
        </div>
      </div>

      <!-- 营养成分详情 -->
      <div class="nutrition-details">
        <h2>营养成分表「每100克可食部」</h2>
        <div class="nutrition-grid">
          <div v-for="item in displayedNutrition" 
               :key="item.nameEn"
               class="nutrition-item">
            <div class="nutrition-name">{{ item.nameCn }}</div>
            <div class="nutrition-content">{{ item.content }}</div>
            <div class="nutrition-status" :style="{ color: getStatusInfo(item.status).color }">
              {{ getStatusInfo(item.status).icon }}
              {{ getStatusInfo(item.status).label }}
            </div>
          </div>
        </div>
        
        <div class="show-more" v-if="foodDetail.nutritionComponents.length > 10">
          <el-button 
            type="primary" 
            link 
            @click="showAllNutrition = !showAllNutrition"
          >
            {{ showAllNutrition ? '收起' : '查看更多营养成分' }}
            <el-icon class="el-icon--right" :class="{ 'is-reverse': showAllNutrition }">
              <ArrowDown />
            </el-icon>
          </el-button>
        </div>
      </div>

      <!-- 关联做法部分 -->
      <div class="related-recipes">
        <h2>相关做法推荐</h2>
        <el-empty description="暂无相关做法" />
      </div>

      <!-- 添加对比对话框 -->
      <el-dialog
        v-model="dialogVisible"
        title="选择对比食品"
        width="60%"
        class="compare-dialog"
      >
        <div class="search-section">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索食品..."
            class="search-input"
            @keyup.enter="handleSearch"
            :prefix-icon="Search"
            clearable
          >
            <template #append>
              <el-button @click="handleSearch">
                搜索
              </el-button>
            </template>
          </el-input>
        </div>

        <div class="compare-list">
          <!-- 对比列表 -->
          <div class="compare-foods">
            <h3>已选择的食品</h3>
            <div class="selected-foods">
              <!-- 当前食品 -->
              <div class="food-card selected">
                <el-image :src="foodDetail?.picture" class="food-image" />
                <div class="food-info">
                  <span class="food-name">{{ foodDetail?.foodName }}</span>
                  <span class="vs-label">当前食品</span>
                </div>
              </div>
              <!-- 已选择的食品 -->
              <div 
                v-for="food in selectedFoods" 
                :key="food.id"
                class="food-card selected"
              >
                <el-image :src="food.picture" class="food-image" />
                <div class="food-info">
                  <span class="food-name">{{ food.foodName }}</span>
                  <el-button 
                    type="danger" 
                    size="small" 
                    class="delete-button"
                    @click.stop="removeFood(food)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 搜索结果区域 -->
          <div class="search-results-container">
            <div v-if="searching" class="search-loading">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>搜索中...</span>
            </div>
            
            <div 
              v-else-if="searchResults.length > 0" 
              class="search-results"
            >
              <div 
                v-for="food in filteredSearchResults" 
                :key="food.id"
                class="food-card"
                @click="addToCompare(food)"
              >
                <el-image :src="food.picture" class="food-image" />
                <div class="food-info">
                  <span class="food-name">{{ food.foodName }}</span>
                  <el-button 
                    type="primary" 
                    size="small" 
                    class="vs-button"
                  >
                    + VS
                  </el-button>
                </div>
              </div>
            </div>
            
            <el-empty 
              v-else-if="searchKeyword && !searching" 
              description="未找到相关食品" 
            />
          </div>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button 
              type="primary" 
              @click="handleCompare" 
              :disabled="selectedFoods.length === 0"
            >
              比较 ({{ selectedFoods.length + 1 }}个食品)
            </el-button>
          </div>
        </template>
      </el-dialog>
    </template>

    <template v-else>
      <el-empty description="未找到相关食品信息" />
    </template>
  </div>
</template>

<style scoped>
.food-detail-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.top-section {
  margin-bottom: 40px;
}

.food-basic-info {
  display: flex;
  gap: 32px;
  align-items: flex-start;
}

.food-image {
  width: 300px;
  height: 300px;
  object-fit: cover;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.info-content {
  flex: 1;
}

.info-content h1 {
  margin: 0 0 16px;
  font-size: 28px;
  color: #303133;
}

.description {
  margin: 16px 0;
  color: #606266;
  line-height: 1.6;
}

.nutrition-ratio-section {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 40px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.ratio-circles {
  display: flex;
  justify-content: center;
  gap: 48px;
  flex-wrap: wrap;
}

.circle-item {
  text-align: center;
}

.circle-item h4 {
  margin: 0;
  font-size: 16px;
  font-weight: normal;
  color: #606266;
}

.circle-value {
  font-size: 20px;
  font-weight: bold;
  margin-top: 8px;
}

.nutrition-details {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.nutrition-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin-top: 24px;
}

.nutrition-item {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
  align-items: center;
}

.nutrition-name {
  color: #303133;
  font-weight: 500;
}

.nutrition-content {
  color: #606266;
  text-align: center;
}

.nutrition-status {
  text-align: right;
  font-weight: 500;
}

.show-more {
  text-align: center;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

h2 {
  font-size: 20px;
  color: #303133;
  margin: 0 0 24px;
  font-weight: 500;
}

.back-button {
  margin-bottom: 20px;
}

.energy-section {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 40px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.energy-display {
  text-align: center;
}

.energy-buttons {
  margin-bottom: 24px;
}

.energy-value-display {
  padding: 32px;
  background: #f5f7fa;
  border-radius: 8px;
  display: inline-block;
  min-width: 200px;
  margin-bottom: 16px;
}

.energy-number {
  font-size: 40px;
  font-weight: bold;
  color: #409EFF;
  line-height: 1.2;
}

.energy-unit {
  margin-top: 8px;
  color: #909399;
  font-size: 14px;
}

.el-progress {
  margin-top: 16px;
}

@media (max-width: 768px) {
  .food-basic-info {
    flex-direction: column;
  }

  .food-image {
    width: 100%;
    height: 200px;
  }

  .nutrition-grid {
    grid-template-columns: 1fr;
  }

  .energy-display {
    flex-direction: column;
    align-items: center;
  }
  
  .ratio-circles {
    gap: 24px;
  }
}

.el-icon.is-reverse {
  transform: rotate(180deg);
}

.related-recipes {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  margin-top: 40px;
  min-height: 300px;
  display: flex;
  flex-direction: column;
}

.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.compare-button {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #4263eb;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.compare-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(66, 99, 235, 0.2);
}

.compare-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.search-section {
  margin-bottom: 24px;
}

.search-input {
  width: 100%;
}

.compare-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.current-food {
  padding: 16px;
  background: #f8fafc;
  border-radius: 12px;
  margin-bottom: 20px;
}

.search-results {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
  padding: 4px;
}

.food-card {
  display: flex;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  background: white;
  border: 1px solid #e5e7eb;
  cursor: pointer;
  transition: all 0.3s ease;
}

.food-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #4263eb;
}

.food-card.selected {
  background: #eef2ff;
  border-color: #4263eb;
}

.food-card .food-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  object-fit: cover;
}

.food-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.food-name {
  font-size: 14px;
  font-weight: 500;
  color: #1a1f36;
}

.vs-label {
  font-size: 16px;
  font-weight: 600;
  color: #4263eb;
}

.vs-button {
  align-self: flex-start;
  padding: 4px 12px;
  font-size: 12px;
}

.dialog-footer {
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
}

/* 自定义滚动条样式 */
.search-results::-webkit-scrollbar {
  width: 6px;
}

.search-results::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.search-results::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.search-results::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* 添加新的样式 */
.compare-foods {
  background: #f8fafc;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 24px;
}

.compare-foods h3 {
  margin: 0 0 16px;
  color: #1a1f36;
  font-size: 16px;
}

.selected-foods {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.delete-button {
  padding: 4px 8px;
  min-height: 24px;
  height: 24px;
}

.delete-button .el-icon {
  margin: 0;
}

.food-card.selected {
  background: #eef2ff;
  border-color: #4263eb;
}

.food-card.selected:first-child {
  background: #e0e7ff;
  border-color: #4263eb;
}

.vs-button {
  align-self: flex-start;
  padding: 4px 12px;
  font-size: 12px;
}

/* 调整搜索结果区域的样式 */
.search-results {
  max-height: 300px;
  overflow-y: auto;
}

/* 添加和修改搜索相关样式 */
.search-results-container {
  position: relative;
  min-height: 100px;
}

.search-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
}

.search-loading .loading-icon {
  font-size: 20px;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.search-input :deep(.el-input-group__append) {
  padding: 0;
}

.search-input :deep(.el-input-group__append button) {
  margin: 0;
  border: none;
  height: 32px;
  padding: 0 16px;
}

.search-input :deep(.el-input__wrapper) {
  padding-right: 8px;
}
</style> 